import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:zrjz/api/auth_repository.dart';
import 'package:zrjz/channel/app_channel.dart';
import 'package:zrjz/comm/constants/api_constants.dart';
import 'package:zrjz/comm/constants/app_constant.dart';
import 'package:zrjz/comm/http/http_result.dart';
import 'package:zrjz/comm/login_intercept/login_intercept_manager.dart';
import 'package:zrjz/comm/utils/event_bus.dart';
import 'package:zrjz/comm/utils/ext_dart.dart';
import 'package:zrjz/comm/utils/log_utils.dart';
import 'package:zrjz/comm/utils/util.dart';
import 'package:zrjz/comm/widget/global_web/global_web_page.dart';
import 'package:zrjz/entity/response/user_login.dart';
import 'package:zrjz/globalService/jverify_service.dart';
import 'package:zrjz/globalService/qq_platform_service.dart';
import 'package:zrjz/globalService/user_service.dart';
import 'package:zrjz/globalService/wx_platform_service.dart';
import 'package:zrjz/modules/auth/bind_phone/bind_phone_page.dart';
import 'package:zrjz/modules/auth/forget_psd/forget_psd_page.dart';
import 'package:zrjz/modules/auth/report_phone_number_dialog.dart';
import 'package:zrjz/modules/auth/sign_up/sign_up_page.dart';
import 'package:zrjz/modules/main/main_page.dart';
import 'login_state.dart';

class LoginController extends GetxController {
  final AuthRepository authRepository = Get.find();
  final LoginState state = LoginState();

  bool isChecked = false;
  bool pwdVisibility = false; //是否明文展示密码
  String? mobilePhoneErrorText; //表单的错误信息展示
  String? passwordErrorText;
  String? mobilePhone; //表单的数据
  String? password;
  bool isInstallQQ = false;
  bool isInstallWx = false;

  // 勾选协议
  void handlerSelectAgreeCheckbox() {
    isChecked = !isChecked;
    update();
  }

  // 切换隐藏密码框
  void switchPwdVisibility() {
    pwdVisibility = !pwdVisibility;
    update();
  }

  // 重置电话的错误文本
  void resetPhoneErrorText() {
    mobilePhoneErrorText = null;
    update();
  }

  /// 执行账号密码的普通登录
  void doInputLogin() {
    mobilePhoneErrorText = null;
    passwordErrorText = null;
    update();

    var phoneController = state.formData['phone']!['controller'];
    var passwordController = state.formData['password']!['controller'];

    mobilePhone = phoneController.text;
    password = passwordController.text;

    Log.d('mobilePhone:$mobilePhone password:$password');

    if (!isChecked) {
      SmartDialog.showToast('请先阅读并同意协议'.tr);
    } else if (Utils.isEmpty(mobilePhone)) {
      mobilePhoneErrorText = "电话号码不能为空";
      update();
    } else if (Utils.isEmpty(password)) {
      passwordErrorText = "密码不能为空";
      update();
    } else {
      //执行密码登录
      _request2LoginPassword();
    }
  }

  /// 请求接口，普通的密码登录
  void _request2LoginPassword() async {
    // //获取到数据
    // SmartDialog.showLoading();
    // String registrationId = UserService.to.getRegistrationId;
    // var result = await authRepository.loginWithPsd(mobilePhone, password, registrationId);
    // SmartDialog.dismiss(status: SmartStatus.loading);
    //
    // //处理数据
    // if (result.isSuccess) {
    //   //保存Token，去首页
    //   _handleLoginSuccess(result.data!);
    // } else {
    //   _handleErrorMessage(result);
    // }
  }

  /// 登录成功的统一处理 - 去首页
  void _handleLoginSuccess(UserLogin result) {
    //保存Token，去首页
    final token = result.token;
    UserService.to.setToken(token);

    //发送通知请求用户详情数据
    bus.emit(AppConstant.eventProfile2Refresh, true);

    //使用SingleTask启动模式去首页
    MainPage.startInstance();
  }

  /// 处理网络请求注册的表单错误
  void _handleErrorMessage(HttpResult<dynamic> result) {
    String? errorMessage = result.errorMsg;
    SmartDialog.showToast(errorMessage ?? '未知错误'.tr);

    Map<String, dynamic>? json = result.getErrorJson();

    handleFormError(json, 'phone', (str) {
      mobilePhoneErrorText = str;
    });
    handleFormError(json, 'password', (str) {
      passwordErrorText = str;
    });
  }

  /// 请求接口，第三方登录 QQ WX Apple
  void _request2LoginSocialite(String platform, String openId) async {
    // //获取到数据
    // SmartDialog.showLoading();
    // String registrationId = UserService.to.getRegistrationId;
    // var result = await authRepository.loginSocialite(platform, openId, registrationId);
    // SmartDialog.dismiss(status: SmartStatus.loading);
    //
    // //处理数据
    // if (result.isSuccess) {
    //   //保存Token，去首页
    //   _handleLoginSuccess(result.data!);
    // } else {
    //   _handleErrorMessage(result);
    //
    //   if (result.code == 101001) {
    //     //第一次登录，需要绑定手机号码
    //     BindPhonePage.startInstance(platform, openId);
    //   }
    // }
  }

  /// 一键登录获取数据成功，执行登录请求
  void _request2LoginJVerify(String token, String loginToken) async {
    // //获取到数据
    // SmartDialog.showLoading();
    // String registrationId = UserService.to.getRegistrationId;
    // var result = await authRepository.loginJVerify(token, loginToken, registrationId);
    // print("########${token}#############${loginToken}###############${registrationId}############");
    // SmartDialog.dismiss(status: SmartStatus.loading);
    //
    // //处理数据
    // if (result.isSuccess) {
    //   //保存Token，去首页
    //   _handleLoginSuccess(result.data!);
    // } else {
    //   _handleErrorMessage(result);
    // }
  }

  /// 第三方QQ登录
  void thirdPartWithQQ() {
    if (!isChecked) {
      SmartDialog.showToast('请先阅读并同意协议'.tr);
    } else {
      //执行登录
      QQPlatformService.to.loginWithQQ((openId) {
        _request2LoginSocialite("qq", openId);
      });

      // _request2LoginSocialite("qq", 'A4F7498DCBFF91DBBF92712F7DAD2729');
    }
  }

  /// 第三方WX登录
  void thirdPartWithWX() async {
    if (!isChecked) {
      SmartDialog.showToast('请先阅读并同意协议'.tr);
    } else {
      //执行登录
      WXPlatformService.to.loginWithWX((openId) {
        _request2LoginSocialite("weixin", openId);
      });

      // _request2LoginSocialite("weixin", 'oI6XH6G7FVU7qHbObYI0lX_E0Das');
    }
  }

  /// 第三方Apple登录
  void thirdPartWithApple() async {
    if (!isChecked) {
      SmartDialog.showToast('请先阅读并同意协议'.tr);
    } else {
      var result = await AppChannel.appleLogin();
      if (Utils.isEmpty(result?["error"])) {
        //执行登录 identityToken
        _request2LoginSocialite("apple", result?["authorizationCode"]);
      } else {
        SmartDialog.showNotify(msg: result?["error"], notifyType: NotifyType.error);
      }
    }
  }

  /// 手机号码一键登录
  void loginQuickWithPhone() {
    if (!isChecked) {
      SmartDialog.showToast('请先阅读并同意协议'.tr);
    } else {
      //执行登录
      JVerifyService.to.loginWithJVerify((token, loginToken) {
        _request2LoginJVerify(token, loginToken);
      });
    }
  }

  /// 去注册页面
  void gotoSignUpPage() {
    SignUpPage.startInstance();
  }

  /// 去忘记密码页面
  void gotoForgetPsdPage() {
    ForgetPsdPage.startInstance();
  }

  /// 底部按钮，展示电话号码
  Future<void> showCallPhone() async {
    _showReportMobileDialog();
  }

  _showReportMobileDialog() {
    SmartDialog.show(
      alignment: Alignment.bottomCenter,
      keepSingle: true,
      builder: (_) => ReportPhoneNumDialog(
        action: (mobile) async {
          final phoneNumber = 'tel:$mobile';
          if (!await launchUrl(Uri.parse(phoneNumber))) throw '无法调用拨打电话';
        },
      ),
    );
  }

  /// 底部按钮，展示人力资源许可证
  void showHRCertificate() {
    GlobalWebPage.startInstance("人力资源许可证", ApiConstants.humanResourcesUrl);
  }

  /// 底部按钮，展示营业执照
  void showBusinessLicense() {
    GlobalWebPage.startInstance("营业执照", ApiConstants.businessLicenseUrl);
  }

  //去Web页面
  void gotoUserAgreementPage() {
    GlobalWebPage.startInstance("免责条款", ApiConstants.userAgreementUrl);
  }

  //去Web页面
  void gotoPricacyPolicyPage() {
    GlobalWebPage.startInstance("隐私协议", ApiConstants.privacyPolicyUrl);
  }

  // =========================== 焦点控制 ===========================

  FocusNode? _phoneFocusNode;
  FocusNode? _passwordFocusNode;

  void _onPhoneFocusChange() {
    if (_phoneFocusNode?.hasFocus == true) {
      mobilePhoneErrorText = null;
      update();
    }
  }

  void _onPasswordFocusChange() {
    if (_passwordFocusNode?.hasFocus == true) {
      passwordErrorText = null;
      update();
    }
  }

  @override
  void onInit() {
    super.onInit();
    _phoneFocusNode = state.formData['phone']!['focusNode'];
    _passwordFocusNode = state.formData['password']!['focusNode'];
  }

  @override
  Future<void> onReady() async {
    super.onReady();
    _phoneFocusNode?.addListener(_onPhoneFocusChange);
    _passwordFocusNode?.addListener(_onPasswordFocusChange);

    var wxResult = await WXPlatformService.to.isInstallWX();
    var qqResult = await QQPlatformService.to.isQQInstalled();
    var qqLiteResult = await QQPlatformService.to.isTIMInstalled();

    isInstallWx = wxResult;
    isInstallQQ = qqResult || qqLiteResult;

    // 都已经到登录页面了，可以预取号
    JVerifyService.to.preLogin();
    update();
  }

  @override
  void onClose() {
    LoginIntercepManager.get().loginFinished();

    super.onClose();
    _phoneFocusNode?.removeListener(_onPhoneFocusChange);
    _passwordFocusNode?.removeListener(_onPasswordFocusChange);
    _phoneFocusNode = null;
    _passwordFocusNode = null;
  }
}
